<template>
    <div id="mapContainer" class="mapContainer">
        <div style="display: flex; position: absolute; bottom: 0; left: 0; z-index: 2">
            <button @click="changeBaseMap('vector')">矢量</button>
            <button @click="changeBaseMap('image')">影像</button>
            <button @click="addyjLayer">预警区</button>
        </div>
        <div id="popupBox" style="padding: 20px; background: #fff; color: #000" v-show="show">
            {{ info.stationname }} {{ info.stationid }} {{ info.rain }}mm
            <span @click="show = false" style="cursor: pointer">x</span>
        </div>
    </div>
</template>

<script setup>
// import { ref } from 'vue';
import Map from '@/map/index';
import jsonData from './anhua.json'; //遮罩层数据
import yjq from './yjq.json'; //遮罩层数据
// import { pointList, weatherPointList } from '@/test/test.js';

let olMap = ref(null); //定义地图实例
let show = ref(false);
let info = ref({});

onMounted(() => {
    olMap.value = new Map('mapContainer');
    olMap.value.layer.initLayer(); //初始化底图

    let extent = olMap.value.layer.initMaskLayer(jsonData); //添加遮罩层,并将范围全局化
    olMap.value.layer.fitExtentPadding({
        extent: extent
    }); //跳转到遮罩层

    // addPolygon();

    // addOverlay();
    // addCollisionPoints();
});
//添加预警图层
const addyjLayer = () => {
    const yjLayer = olMap.value.layer.createVectorLayer('预警图层', 35);
    yjLayer.getSource().clear();
    const arr = yjq.map(item => {
        return {
            color: item.color,
            points: item.posArr.map(item1 => {
                return [item1.lon, item1.lat]
            })

        }
    })
    olMap.value.layer.addGridArea(arr)
}
const addPrj = () => {
    let layerList = ref([]);
    //dimgis工程地图chinaProject,/dmgis用来配置代理
    let dmProjectLayer = new dmgis.olmap.ServiceLayer(prjName, '/dmgis', {
        minZoom: 1,
        tileSize: [256, 256]
    });
    //获取工程的所有图层
    dmProjectLayer.InitService().then((res) => {
        layerList.value = res.RESPONSE.SERVER.LAYER;
    });
};

const query = (sql) => {
    //查询参数构建
    let getfeaturePoint = dmProjectLayer.GetFeatureMapService();

    // getfeaturePoint.type = "1"//索引
    // getfeaturePoint.strlist = "1,2,3,4"

    // getfeaturePoint.type = "2"//实体号
    // getfeaturePoint.strlist = "1,2,3,4"

    getfeaturePoint.type = '0'; //条件
    getfeaturePoint.strlayername = form.layer;
    getfeaturePoint.sql.strSql = sql && sql.length ? sql : 'dmgis_id > 0';

    // var rect = new dmgis.object.Envelope();
    // rect.minx
    // getfeaturePoint.sql.env  = rect;//矩形
    // getfeaturePoint.sql.strPos = "";//多边形

    dmProjectLayer.SendFeatureMapService(getfeaturePoint).then((res) => {
        if (res) {
            ElMessage.success('查询成功');

            layerName = form.layer; //存放当前表格的图层名
            //请求与表格结果对应的工程图片
            getPrjImgParam = {
                name: 'QUERY',
                singleLabel: true,
                attributes: {
                    where: sql && sql.length ? sql : 'dmgis_id > 0'
                }
            };
            addDmProject();

            temporaryPolygonArr = []; //重置为条件查询
            //两种情况，返回结果为对象则转为数组用来渲染表格
            if (!Object.hasOwn(res.RESPONSE.FEATURES, 'FEATURE') && res.RESPONSE.FEATURES) {
                tableData.value = [];
            } else if (res.RESPONSE.FEATURES.FEATURE.length) {
                tableData.value = res.RESPONSE.FEATURES.FEATURE;
            } else {
                tableData.value = [res.RESPONSE.FEATURES.FEATURE];
            }
            calculatePagedData(); //分页计算
            tableShow.value = true;
            // console.log(tableData.value);
        } else {
            ElMessage.error('查询失败');
        }
    });
};

let polygonLayer = null;



//加地图弹窗
let overlay;
//两个参数，第一个为绑定的dom，第二个为点击事件返回的一个feature，拿到feature处理相应逻辑
const addOverlay = () => {
    overlay = olMap.value.overlay.setOverlay(document.getElementById('popupBox'), (feature) => {
        //如果feature有相应属性
        if (feature.pointInfo) {
            overlay.setPosition(feature.values_.geometry.flatCoordinates); //设置弹窗位置
            //......弹窗处理逻辑

            info.value = feature.pointInfo;
            show.value = true;
        }
    });
};

const getColorByRainfall = (value) => {
    // 区间定义：[下限, 颜色(10进制)]
    const ranges = [
        [0, 16777215], // 0-0.1
        [0.1, 7190413], // 0.1-1.6
        [1.6, 3582517], // 1.6-7
        [7, 12096843], // 7-15
        [15, 16711680], // 15-40
        [40, 11665596], // 40-50
        [50, 3280484] // >= 50
    ];

    // 找到第一个满足 value < ranges[i+1][0] 的区间
    for (let i = 0; i < ranges.length; i++) {
        const next = ranges[i + 1];
        if (!next || value < next[0]) {
            // 把 10 进制颜色转成 16 进制字符串
            return '#' + ranges[i][1].toString(16).padStart(6, '0').toUpperCase();
        }
    }
    // 兜底
    return '#0032F4';
};

//添加碰撞点
let collisionLayer = null;
const addCollisionPoints = () => {
    let features = [];
    weatherPointList.forEach((point) => {
        features.push(
            olMap.value.vector.setCollisionPoint({
                coordinates: [Number(point.lon), Number(point.lat)],
                style: {
                    radius: 5,
                    fillColor: getColorByRainfall(Number(point.rain)),
                    strokeColor: getColorByRainfall(Number(point.rain))
                },
                info: {
                    name: 'pointInfo',
                    info: point
                }
            })
        );
    });

    collisionLayer = olMap.value.vector.addCollisionPoints({
        features: features,
        distance: 15
    });
};

//移除碰撞点
const clearCollisionPoints = () => { };



//切换底图
const changeBaseMap = (type) => {
    olMap.value.layer.changeBaseMap(type);
};

onBeforeUnmount(() => {
    if (olMap.value) {
        // 清理地图资源
        olMap.value.layer.disposeMap();
    }
});
</script>

<style>
.mapContainer {
    width: 100%;
    height: 91vh;
    position: relative;
}
</style>
